package com.declum.peyar.handler;

/**
 * This class store the information about Client's lock request. There are four
 * fields to lock/renew/release path.
 * 
 * They are ClientName, Operation_Type, LockPath and LockKey(Other than
 * acquiring lock)
 * 
 * @author clement
 * 
 */
public class RequestHeader {
	String address;
	String command;
	String serviceName;

	/**
	 * @return address in the request
	 */
	public String getAddress() {
		return this.address;
	}

	/**
	 * @return command in the request
	 */
	public String getCommand() {
		return this.command;
	}

	/**
	 * @return Service Name in the request
	 */
	public String getServiceName() {
		return this.serviceName;
	}

	/**
	 * This returns true/false based on the completeness of the header. For now
	 * it'll just returns true if all values are not null.
	 * 
	 * @return
	 */
	public boolean isComplete() {
		boolean flag = (this.serviceName != null) && (this.command != null);
		if (flag) {
			if (!this.command.toLowerCase().endsWith("lookup")) {
				flag = flag && (this.address != null);
			}
		}
		return flag;
	}

	/**
	 * It parses the String as key/value pair from "key: value" format. Returns
	 * true of successfully parser, else false.
	 * 
	 * @param data
	 *            string to be parsed
	 * @return
	 * @throws RequestParserException
	 */
	public boolean parse(String data) throws RequestParserException {
		String[] part = data.split("\\s*:\\s*");
		if (part.length == 2) {
			if (part[0].toLowerCase().equals("name")) {
				this.serviceName = part[1].trim();
			} else if (part[0].toLowerCase().equals("address")) {
				this.address = part[1].trim();
			} else if (part[0].toLowerCase().equals("command")) {
				this.command = part[1].trim();
			} else {
				throw new RequestParserException("Unknown Key" + part[0]);
			}
			return true;
		} else {
			throw new RequestParserException("Not a proper line '" + data + "'");
		}
	}
}
